import axios from 'axios'

import { BASE_URL, TIMEOUT } from './config.js'

class HYRequest {
    constructor(BASE_URL, TIMEOUT) {
        this.instance = axios.create({
            baseURL: BASE_URL,
            timeout: TIMEOUT
        })

        this.instance.interceptors.request.use(
            config => {
                const token = localStorage.getItem('token')
                if(token) {
                    config.headers['token'] = `${token}`
                }
                return config
            }
        )
    }

    request(config) {
        return new Promise((resolve, reject) => {
            this.instance.request(config).then(res => {
                resolve(res.data)
            }).catch(err => {
                reject(err)
            })
        })
    }

    get(config) {
        return this.request({ ...config, method: "get" })
    }

    post(config) {
        return this.request({ ...config, method: "post" })
    }

    patch(config) {
        return this.request({ ...config, method: "patch"})
    }

}

export default new HYRequest(BASE_URL, TIMEOUT)